#pragma once

#ifndef _USINGPOOL_
#define _USINGPOOL_

#include <vector>

template <typename T>
class UsingPool
{
public:
	static T* IsUsing(T* pT);
	static bool Add(T* pT);
	static bool Remove(T* pT);
	static size_t GetSize();
	static T* GetAt(size_t i);
private:
	static UsingPool& GetInstance();
	UsingPool(void);
	~UsingPool(void);

private:
	std::vector<T*> m_UsingPool;
};

//**********************************************************************

//**********************************************************************
template <typename T>
UsingPool<T>& UsingPool<T>::GetInstance()
{
	static UsingPool inst;
	return inst;
}

template <typename T>
UsingPool<T>::UsingPool(void)
{
}

template <typename T>
UsingPool<T>::~UsingPool(void)
{
}

template <typename T>
T* UsingPool<T>::IsUsing(T* pT)
{
	if(!pT)
		return NULL;

	std::vector<T*>& m_UsingPool = GetInstance().m_UsingPool;

	size_t size = m_UsingPool.size();

	for(size_t i=0; i<size; i++) {
		T* p = m_UsingPool[i];
		if( (p==pT) || (*p==*pT))
			return p;
	}
	return NULL;
}

template <typename T>
bool UsingPool<T>::Add(T* pT)
{
	if(NULL == pT)
		return false;

	std::vector<T*>& m_UsingPool = GetInstance().m_UsingPool;

	if(!IsUsing(pT)) {
		m_UsingPool.push_back(pT);
		return true;
	}
	return false;
}

template <typename T>
bool UsingPool<T>::Remove(T* pT)
{
	if(NULL == pT)
		return false;

	std::vector<T*>& m_UsingPool = GetInstance().m_UsingPool;

	size_t size = m_UsingPool.size();
	for(size_t i=0; i<size; i++) {
		T* p = m_UsingPool[i];
		if(p==pT) {
			m_UsingPool.erase(m_UsingPool.begin()+i);
			if(m_UsingPool.empty())
				m_UsingPool.clear();
			return true;
		}
	}

	return false;
}

template <typename T>
size_t UsingPool<T>::GetSize()
{
	return GetInstance().m_UsingPool.size();
}

template <typename T>
T* UsingPool<T>::GetAt( size_t i )
{
	if(0<=i && i<GetSize()) {
		return GetInstance().m_UsingPool[i];
	}

	return NULL;
}

#endif /* _USINGPOOL_ */